/**
 * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
 * This file is part of CSipSimple.
 *
 *  CSipSimple is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  If you own a pjsip commercial license you can also redistribute it
 *  and/or modify it under the terms of the GNU Lesser General Public License
 *  as an android library.
 *
 *  CSipSimple is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CSipSimple.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.mcptt.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;

import com.cloudptt.api.product.log.Log;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.ConfigFileInfo;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.GroupMembInfo;
import com.mcptt.db.model.HistoryInfo;
import com.mcptt.db.model.MapPointInfo;
import com.mcptt.db.model.OnlineInfo;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.db.model.SessionReadStatus;
import com.mcptt.db.model.UserInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class DBAdapter {
	//    private final static String THIS_FILE = "DBAdapter";

	private final Context context;
	private DatabaseHelper databaseHelper;
	private boolean opened = false;

	public DBAdapter(Context aContext) {
		Log.debug(this.getClass(), "DBAdapter");
		context = aContext;
		databaseHelper = new DatabaseHelper(context);
	}

	public void doExit(){
		close();
	}
	/**
	 * Open database
	 *
	 * @return database adapter
	 * @throws SQLException
	 */
	public DBAdapter open() throws SQLException {
		databaseHelper.getWritableDatabase();
		opened = true;
		return this;
	}

	/**
	 * Close database
	 */
	public void close() {
		databaseHelper.close();
		opened = false;
	}

	public boolean isOpen() {
		return opened;
	}
	//	public List<GroupInfo> getGroupListAndUserList(){
//		List<GroupInfo> list = new ArrayList<GroupInfo>();
//		GroupInfo groupInfo = new GroupInfo("sip:14980025101@crsc.mcx.mnc020.mcc460.5gr","group1");
//
//		List<UserInfo> userInfoList = new ArrayList<UserInfo>();
//		UserInfo info = new UserInfo("14980024101");
//		boolean add = userInfoList.add(info);
//		info = new UserInfo("14980024102");
//		userInfoList.add(info);
//		info = new UserInfo("14980024103");
//		userInfoList.add(info);
//		info = new UserInfo("14980024104");
//		userInfoList.add(info);
//		info = new UserInfo("14980024105");
//		userInfoList.add(info);
//		info = new UserInfo("14980024106");
//		userInfoList.add(info);
//
//		groupInfo.setUserList(userInfoList);
//		list.add(groupInfo);
////		}
////		if (cursor != null) cursor.close();
//		return list;
//	}
//	public List<GroupInfo> getGroupListAndUserList(){
//		Cursor cursor = databaseHelper.rawQuery("select * from "+DbConst.Table_GroupAddress +" order by " +DbConst.COL_Attr + " desc ," +DbConst.COL_AddrId + " asc",new String[]{});
//		List<GroupInfo> list = new ArrayList<GroupInfo>();
//		while (cursor != null && cursor.moveToNext()) {
//			GroupInfo info = new GroupInfo(cursor);
//			List<UserInfo> userInfoList = getOnlineUserInfoList(info.getAddrId());
//			info.setUserList(userInfoList);
//			list.add(info);
//		}
//		if (cursor != null) cursor.close();
//		return list;
//	}
	public List<AddrInfo> getAddrInfoList() {
		Cursor cursor = databaseHelper.query(true,DbConst.View_AddressList,AddrInfo.getColumns(),null,null,null,null,DbConst.COL_Type + " asc ," + DbConst.COL_Attr + " desc",null);
		List<AddrInfo> list = new ArrayList<AddrInfo>();
		while (cursor != null && cursor.moveToNext()) {
			AddrInfo info = new AddrInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}
	public List<AddrInfo> getAddrInfoList(boolean isGroup) {
		Cursor cursor = null;
		if(isGroup) {
			cursor = databaseHelper.query(true, DbConst.Table_GroupAddress, AddrInfo.getColumns(), null, null, null, null, DbConst.COL_Type + " asc ," + DbConst.COL_Attr + " desc", null);
		}
		else
		{
			cursor = databaseHelper.query(true, DbConst.Table_Address, AddrInfo.getColumns(), null, null, null, null, DbConst.COL_Type + " asc ," + DbConst.COL_Attr + " desc", null);
		}
		List<AddrInfo> list = new ArrayList<AddrInfo>();
		while (cursor != null && cursor.moveToNext()) {
			AddrInfo info = new AddrInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}
//	public List<GroupInfo> getGroupListAndUserList(){
//		Cursor cursor = databaseHelper.rawQuery("select * from "+DbConst.Table_GroupAddress +" order by " +DbConst.COL_Attr + " desc ," +DbConst.COL_AddrId + " asc",new String[]{});
//		List<GroupInfo> list = new ArrayList<GroupInfo>();
//		while (cursor != null && cursor.moveToNext()) {
//			GroupInfo info = new GroupInfo(cursor);
//			List<UserInfo> userInfoList = getOnlineUserInfoList(info.getAddrId());
//			info.setUserList(userInfoList);
//			list.add(info);
//		}
//		if (cursor != null) cursor.close();
//		return list;
//	}

	public List<GroupInfo> getGroupInfoList(){
		Cursor cursor = databaseHelper.rawQuery("select * from "+DbConst.Table_GroupAddress +" order by " +DbConst.COL_AddrId+" desc",null);
		List<GroupInfo> list = new ArrayList<GroupInfo>();
		while (cursor != null && cursor.moveToNext()) {
			GroupInfo info = new GroupInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}

	public GroupInfo getDefaultGroupInfo()
	{
		String selection = DbConst.COL_Attr + " = ? ";
		Cursor cursor = databaseHelper.query(true,DbConst.Table_GroupAddress,GroupInfo.getColumns(),selection,new String[]{"1"},null,null,null,null);
		GroupInfo info = null;
		if(cursor != null
				&& cursor.moveToNext())
		{
			info =  new GroupInfo(cursor);
		}
		if (cursor != null) cursor.close();
		return info;
	}
	public AddrInfo findGroupInfoByNum(String num)
	{
		Log.debug(this.getClass(),"findGroupInfoByNum num = " + num);
		String selection = DbConst.COL_AddrId + " = ? ";
		Cursor cursor = databaseHelper.query(true,DbConst.Table_GroupAddress,GroupInfo.getColumns(),selection,new String[]{num},null,null,null,null);
		AddrInfo info = null;
		if(cursor != null
				&& cursor.moveToNext())
		{
			info =  new GroupInfo(cursor);
		}
		if (cursor != null) cursor.close();
		if(info == null)
		{
			info = new AddrInfo(GroupInfo.GroupType_Normal,"G_"+num,num,0);
			if(info.isEmergencyNum())
			{
				info.setType(GroupInfo.GroupType_Crsc);
				info.setName("299");
				info.setAddrId("50299");
			}
			if(info.isCall210())
			{
				info.setType(GroupInfo.GroupType_Crsc);
				info.setName("210");
				info.setAddrId("50210");
			}
		}
		return info;
	}

	public long addGroupInfo(GroupInfo info){
		Log.debug(getClass(), "addGroupInfo info = " + info);
//		databaseHelper.rawQuery("delete from "+DbConst.Table_GroupAddress +" where " + DbConst.COL_Id + " = ",new String[]{info.getMcId()});
		databaseHelper.delete(DbConst.Table_GroupAddress,DbConst.COL_AddrId + "=?",new String[]{info.getAddrId()});
		Log.debug(getClass(), "addGroupInfo");
		long result =  databaseHelper.insert(DbConst.Table_GroupAddress,null,info.getContentValues());
		Log.debug(getClass(), "addGroupInfo result = " + result);
		return result;
	}

	public long deleteAllGroupInfo(){
		Log.debug(getClass(), "deleteAllGroupInfo");
		return databaseHelper.delete(DbConst.Table_GroupAddress,null,null);
	}

	public long updateGroupInfo(GroupInfo info){
		String selection = DbConst.COL_AddrId + " = ?";
		long result = databaseHelper.update(DbConst.Table_GroupAddress,info.getContentValues(),selection,new String[]{info.getAddrId()});
		Log.debug(getClass(), "updateGroupInfo result = " + result);
		return result;
	}

//	public long setDefatuleGroupInfo(GroupInfo info){
//		Log.debug(getClass(), "setDefatuleGroupInfo info = " + info);
//		databaseHelper.execSQL(DbConst.UPDATE_DEFAULT_GROUP);
//		String selection = DbConst.COL_AddrId + " = ?";
//		long result =  databaseHelper.update(DbConst.Table_GroupAddress,info.getSetDefaultGroupInfoContentValues(),selection,new String[]{info.getAddrId()});
//		Log.debug(getClass(), "updateGroupInfo result = " + result);
//		return result;
//	}

	public long setDefatuleGroupInfo(AddrInfo info){
		Log.debug(getClass(), "setDefatuleGroupInfo info = " + info);
		databaseHelper.execSQL(DbConst.UPDATE_DEFAULT_GROUP);
		String selection = DbConst.COL_AddrId + " = ?";
		long result =  databaseHelper.update(DbConst.Table_GroupAddress,info.getSetDefaultGroupInfoContentValues(),selection,new String[]{info.getAddrId()});
		Log.debug(getClass(), "updateGroupInfo result = " + result);
		return result;
	}

	public List<UserInfo> getUserInfoList(String groupId){
		Cursor cursor = databaseHelper.query(true,DbConst.Table_Address,UserInfo.getColumns(),DbConst.COL_GroupId+" =?",new String[]{groupId},null,null,null,null);
		List<UserInfo> list = new ArrayList<UserInfo>();
		while (cursor != null && cursor.moveToNext()) {
			UserInfo info = new UserInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}

	public List<UserInfo> getUserInfoList(){
		Cursor cursor = databaseHelper.query(true,DbConst.Table_Address,UserInfo.getColumns(),null,null,null,null,null,null);
		List<UserInfo> list = new ArrayList<UserInfo>();
		while (cursor != null && cursor.moveToNext()) {
			UserInfo info = new UserInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}


	public long addUserInfo(UserInfo info){
		Log.debug(this.getClass(),"addUserInfo info = " + info);
		String selection = DbConst.COL_AddrId + " = ?  ";
//		databaseHelper.rawQuery("delete from "+DbConst.Table_Address +" where " + DbConst.COL_Id + "=" +new String[]{info.getMcId()},null);
		databaseHelper.delete(DbConst.Table_Address,selection,new String[]{info.getAddrId()});
		Log.debug(this.getClass(),"addUserInfo");
		long result = databaseHelper.insert(DbConst.Table_Address,null,info.getContentValues());
		Log.debug(this.getClass(),"addUserInfo result = " + result);
		return result;
	}

	public long addMembInfo(GroupMembInfo info){
		Log.debug(this.getClass(),"addMembInfo info = " + info);
		String selection = DbConst.COL_AddrId + " = ?  and " +DbConst.COL_GroupId + " = ?";
//		databaseHelper.rawQuery("delete from "+DbConst.Table_Address +" where " + DbConst.COL_Id + "=" +new String[]{info.getMcId()},null);
		databaseHelper.delete(DbConst.TABLE_MEMBER,selection,new String[]{info.getAddrId(),info.getGroupAddrId()});
		long result = databaseHelper.insert(DbConst.TABLE_MEMBER,null,info.getContentValues());
		Log.debug(this.getClass(),"addMembInfo result = " + result);
		return result;
	}

	public void delAllMembInfo(String groupAddrId){
		Log.debug(this.getClass(),"delAllMembInfo groupAddrId = " + groupAddrId);
		String selection =DbConst.COL_GroupId + " = ?";
//		databaseHelper.rawQuery("delete from "+DbConst.Table_Address +" where " + DbConst.COL_Id + "=" +new String[]{info.getMcId()},null);
		databaseHelper.delete(DbConst.TABLE_MEMBER,selection,new String[]{groupAddrId});
	}

	public List<GroupMembInfo> getGroupMembInfoList(AddrInfo info,String selfAddrId){
		Log.debug(this.getClass(),"getGroupMembInfoList info = " + info + " selfAddrId = " + selfAddrId);
		String selection = DbConst.COL_GroupId + " = ? and "+ DbConst.COL_AddrId + " <> ? ";
		Log.debug(this.getClass(),"getGroupMembInfoList selection = " + selection);
		Cursor cursor = databaseHelper.query(true,DbConst.TABLE_MEMBER,GroupMembInfo.getColumns(),selection,new String[]{info.getAddrId(),selfAddrId},null,null,null,null);
		List<GroupMembInfo> list = new ArrayList<GroupMembInfo>();
		while (cursor != null && cursor.moveToNext()) {
			GroupMembInfo membInfo = new GroupMembInfo(cursor);
			Log.debug(this.getClass(),"getGroupMembInfoList membInfo = " + membInfo);
			list.add(membInfo);
		}
		if (cursor != null) cursor.close();
		Collections.sort(list);
		return list;
	}

	public void resetGroupMembStatus(String groupAddrId){
		Log.debug(this.getClass(),"resetGroupMembStatus groupAddrId = " + groupAddrId );
		String sqlStr = "update " + DbConst.TABLE_MEMBER + " set attr = 0 where groupId = " + groupAddrId;
		databaseHelper.execSQL(sqlStr);
	}

	public long addSessionReadStatus(SessionReadStatus info)
	{
		String selection = DbConst.COL_ConversationId + " = ? and " + DbConst.COL_MsgId + " = ? and " + DbConst.COL_GroupId + " = ? and " + DbConst.COL_AddrId + " = ? ";
//		databaseHelper.rawQuery("delete from "+DbConst.Table_Address +" where " + DbConst.COL_Id + "=" +new String[]{info.getMcId()},null);
		databaseHelper.delete(DbConst.Table_Session_Group_Status,selection,new String[]{info.getConversationId(),info.getMsgId(),info.getGroupId(),info.getAddrId()});
		long result = databaseHelper.insert(DbConst.Table_Session_Group_Status,null,info.getContentValues());
		Log.debug(this.getClass(),"addSessionReadStatus result = " + result);
		return result;
	}
	public List<SessionReadStatus> getSessionReadStatusList(SessionInfo info){

		String groupId = info.getPeerAddrInfo().getAddrId();
		Log.debug(this.getClass(),"getSessionReadStatusList groupId = " + groupId);
		String str = DbConst.getMessageStatusQueryStr(info.getConversationId(),info.getMsgId(),groupId);
		Cursor cursor = databaseHelper.rawQuery(str,null);
		List<SessionReadStatus> readStatusList = new ArrayList<SessionReadStatus>();
		while (cursor != null && cursor.moveToNext()) {
			SessionReadStatus status = new SessionReadStatus(cursor);
			Log.debug(this.getClass(),"getSessionReadStatusList status = " + status);
			readStatusList.add(status);
		}
		if (cursor != null) cursor.close();
		Log.debug(this.getClass(),"getSessionReadStatusList readStatusList = " + readStatusList);

		String selection = DbConst.COL_GroupId + " = ?  ";
		cursor = databaseHelper.query(true,DbConst.TABLE_MEMBER,SessionReadStatus.getColumns(),selection,new String[]{groupId},null,null,null,null);
		List<SessionReadStatus> memberList = new ArrayList<SessionReadStatus>();
		while (cursor != null && cursor.moveToNext()) {
			SessionReadStatus memberInfo = new SessionReadStatus(cursor);
			memberList.add(memberInfo);
		}
		if (cursor != null) cursor.close();
		Log.debug(this.getClass(),"getSessionReadStatusList memberList = " + memberList);
		List<SessionReadStatus> memberStatusList = new ArrayList<SessionReadStatus>();
		for(Iterator<SessionReadStatus> itor = readStatusList.iterator();itor.hasNext();)
		{
			SessionReadStatus readStatus = itor.next();
			if(readStatus != null)
			{
				String readStatusAddrId = readStatus.getAddrId();
				int status = readStatus.getStatus();
				Log.debug(this.getClass(),"getSessionReadStatusList readStatusAddrId = " + readStatusAddrId + " status = " + status);
				for (Iterator<SessionReadStatus> membItor = memberList.iterator(); membItor.hasNext(); ) {
					SessionReadStatus member = membItor.next();
					String memberAddrId = member.getAddrId();
					Log.debug(this.getClass(),"getSessionReadStatusList memberAddrId = " + memberAddrId);
					if (memberAddrId != null
							&& memberAddrId.equals(readStatusAddrId))
					{
						member.setStatus(status);
					}
				}
			}
		}
		Collections.sort(memberList);
		Log.debug(this.getClass(),"getSessionReadStatusList after memberList = " + memberList);
		return memberList;
	}

	public long updateUserInfo(UserInfo info)
	{
		Log.debug(this.getClass(),"updateUserInfo info = " + info);
		String selection = DbConst.COL_AddrId + " = ? ";
		boolean isExist = databaseHelper.checkRecordExists(DbConst.Table_Address,selection,new String[]{info.getAddrId()});
		if(isExist)
		{
			return databaseHelper.update(DbConst.Table_Address,info.getContentValues(),selection,new String[]{info.getAddrId()});
		}
		else
		{
			return databaseHelper.insert(DbConst.Table_Address,null,info.getContentValues());
		}
	}
	public long deleteAllUserInfo(){
		return databaseHelper.delete(DbConst.Table_Address,null,null);
	}
	public UserInfo findUserInfoByNum(String num)
	{
		Log.debug(this.getClass(),"findUserInfoByNum num = " + num);
		String selection = DbConst.COL_AddrId + " = ? ";
		Cursor cursor = databaseHelper.query(true,DbConst.Table_Address,AddrInfo.getColumns(),selection,new String[]{num},null,null,null,null);
		UserInfo info = null;
		if(cursor != null
				&& cursor.moveToNext())
		{
			info =  new UserInfo(cursor);
		}
		if (cursor != null) cursor.close();
		if(info == null)
		{
			info = new UserInfo(num,"");
		}
		return info;
	}

	public void queryLargeUserInfoList(String groupId,Callback callback)
	{
		String selection = DbConst.COL_GroupId + " = " + groupId;
		String sqlStr = DbConst.QUERY_LOGINSTATE + selection + DbConst.QUERY_LOGINSTATE_ORDER;
		databaseHelper.queryLargeData(sqlStr,callback);
	}

	public List<UserInfo> getOnlineUserInfoList(String groupId){
//		Cursor cursor = databaseHelper.rawQuery("select * from "+DbConst.Table_LoginState +" where " + DbConst.COL_GroupId+" =? order by id desc",new String[]{groupId});
		String selection = DbConst.COL_GroupId + " = " + groupId;
		String sqlStr = DbConst.QUERY_LOGINSTATE + selection + DbConst.QUERY_LOGINSTATE_ORDER;
		Log.debug(this.getClass(),"getOnlineUserInfoList sqlStr = " + sqlStr);
		Cursor cursor = databaseHelper.rawQuery(sqlStr,null);
		List<UserInfo> list = new ArrayList<UserInfo>();
		while (cursor != null && cursor.moveToNext()) {
			UserInfo info = new UserInfo(cursor);
			Log.debug(this.getClass(),"getOnlineUserInfoList info = " + info);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}

	public long addOnlineInfo(OnlineInfo info){
		Cursor cursor = databaseHelper.rawQuery("delete from "+DbConst.Table_LoginState +" where " + DbConst.COL_UserId + " = ",new String[]{info.getUserId()});
		return databaseHelper.insert(DbConst.Table_LoginState,null,info.getContentValues());
	}
	public List<MapPointInfo> getMapPointInfoList(){
		Cursor cursor = databaseHelper.query(true,DbConst.Table_Map_Point,MapPointInfo.getColumns(),null,null,null,null,null,null);
		List<MapPointInfo> list = new ArrayList<MapPointInfo>();
		while (cursor != null && cursor.moveToNext()) {
			MapPointInfo info = new MapPointInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}



	public List<HistoryInfo> getHistoryInfoList()
	{
		Log.debug(this.getClass(),"getHistoryInfoList");
		List<HistoryInfo> list = new ArrayList<HistoryInfo>();
		Log.debug(this.getClass(),"getHistoryInfoList sqlStr = " + DbConst.QUERY_HIRSTORY);
//		Cursor cursor = databaseHelper.query(true,DbConst.Table_History,HistoryInfo.getColumns(),null,null,null,null,DbConst.COL_Affiliation + " desc, " + DbConst.COL_FromType + " asc, "+ DbConst.COL_LastMsgDate +" desc",null);
		Cursor cursor = databaseHelper.rawQuery(DbConst.QUERY_HIRSTORY,null);
		while (cursor != null && cursor.moveToNext()) {
			HistoryInfo info = new HistoryInfo(cursor);
			list.add(info);
		}
		if (cursor != null) cursor.close();
		return list;
	}

	public void queryLargeHistoryList(Callback callback)
	{
		String sqlStr = DbConst.QUERY_HIRSTORY;
		databaseHelper.queryLargeData(sqlStr,callback);
	}


	public boolean hasNewMsg()
	{
		return true;
	}
	public void queryLargeSessionList(String mcId,Callback callback)
	{
		String sqlStr = DbConst.QUERY_SESSION_NEW + mcId ;
		Log.debug(this.getClass(),"queryLargeSessionList sqlStr = " + sqlStr);
		databaseHelper.queryLargeData(sqlStr,callback);
	}
//	public void queryLargeFuncSessionList(Callback callback)
//	{
//		String sqlStr = DbConst.QUERY_FUNC_SESSION_NEW + SessionInfo.Type_Func;
//		Log.debug(this.getClass(),"queryLargeSessionList sqlStr = " + sqlStr);
//		databaseHelper.queryLargeData(sqlStr,callback);
//	}
	public void insertNewSession(SessionInfo session, boolean isClear)
	{
		Log.debug(this.getClass(),"insertNewSession session = " + session);
		String selection = DbConst.COL_ConversationId + " = ? and " + DbConst.COL_MsgId + " = ? ";
		boolean isExist = databaseHelper.checkRecordExists(DbConst.Table_Session,selection,new String[]{session.getConversationId(),session.getMsgId()});
		Log.debug(this.getClass(),"insertNewSession isExist = " + isExist);
		if(!isExist) {
			databaseHelper.insert(DbConst.Table_Session, null, session.getContentValues());
//			if(!session.isFuncMsg()) {
			HistoryInfo info = session.toHistoryInfo();
			Log.debug(this.getClass(), "insertNewSession HistoryInfo = " + info);
			insertOrUptHistoryInfo(info, isClear);
//			}
		}
	}

	public void updateSession(String conversationId,String msgId,int status)
	{
		Log.debug(this.getClass(),"updateSession conversationId = " + conversationId + " msgId = " + msgId + " status = " + status);
		String selection =  DbConst.COL_ConversationId + " = ? AND " + DbConst.COL_MsgId + " = ? and " + DbConst.COL_Status + " < " + status;
		databaseHelper.update(DbConst.Table_Session, SessionInfo.getUpdateStatusContentValues(status), selection, new String[]{conversationId,msgId});
	}
	public void updateSession(SessionInfo info)
	{
		String conversationId = info.getConversationId();
		String msgId = info.getMsgId();
		Log.debug(this.getClass(),"updateSessionInfo conversationId = " + conversationId + " msgId = " + msgId);
		String selection =  DbConst.COL_ConversationId + " = ? AND " + DbConst.COL_MsgId + " = ? ";
		databaseHelper.update(DbConst.Table_Session, info.getContentValues(), selection, new String[]{conversationId,msgId});
	}
	public void insertOrUptHistoryInfo(HistoryInfo info,boolean isClear)
	{
		String selection = DbConst.COL_PeerAddrId + " = ? ";
		boolean isExist = databaseHelper.checkRecordExists(DbConst.Table_History,selection,new String[]{info.getPeerAddrInfo().getAddrId()});
		Log.debug(this.getClass(),"insertOrUptHistoryInfo isExist = " + isExist);
		if(isExist) {
			if (isClear)
			{
				info.setUnreadCount(0);
				updateHirstory(info,isClear);
			} else
			{
				updateHirstory(info,isClear);
				String sqlStr = DbConst.UPDATE_HISTORY_UNREAD + info.getPeerAddrInfo().getAddrId();
				Log.debug(this.getClass(),"insertOrUptHistoryInfo sqlStr = " + sqlStr);
				databaseHelper.execSQL(sqlStr);
			}
		}
		else
		{
			addHirstory(info);
		}
	}
	private boolean addHirstory(HistoryInfo info)
	{
		databaseHelper.insert(DbConst.Table_History,null,info.getContentValues());
		return true;
	}
	private boolean updateHirstory(HistoryInfo info,boolean isClear)
	{
		String selection = DbConst.COL_PeerAddrId + " = ? ";
		if(isClear) {
			databaseHelper.update(DbConst.Table_History, info.getUpdateContentValues(), selection, new String[]{info.getPeerAddrInfo().getAddrId()});
		}
		else
		{
			databaseHelper.update(DbConst.Table_History, info.getUpdateContentValuesExceptUnreadCount(), selection, new String[]{info.getPeerAddrInfo().getAddrId()});
		}
		return true;
	}
	public boolean delHirstory(String peerAddrId)
	{
		Log.debug(this.getClass(),"delHirstory peerAddrId = " + peerAddrId);
		String selection = DbConst.COL_PeerAddrId + " = ? ";
		databaseHelper.delete(DbConst.Table_History,selection,new String[]{peerAddrId});
		delAllSession(peerAddrId);
		return true;
	}
	public boolean delAllSession(String peerAddrId)
	{
		Log.debug(this.getClass(),"delSession peerAddrId = " + peerAddrId);
		String selection =  DbConst.COL_PeerAddrId + " = ? ";
		databaseHelper.delete(DbConst.Table_Session,selection,new String[]{peerAddrId});
		return true;
	}
	public boolean delSession(SessionInfo info)
	{
		String conversationId = info.getConversationId();
		String msgId = info.getMsgId();
		Log.debug(this.getClass(),"delSession conversationId = " + conversationId + " msgId = " + msgId);
		String selection =  DbConst.COL_ConversationId + " = ? AND " + DbConst.COL_MsgId + " = ?  ";
		databaseHelper.delete(DbConst.Table_Session,selection,new String[]{conversationId,msgId});
		return true;
	}
	public void resetSessionCount(AddrInfo fromId)
	{
		String sqlStr =DbConst.RESET_HISTORY_UNREAD + fromId.getAddrId();
		Log.debug(this.getClass(),"insertOrUptHistoryInfo sqlStr = " + sqlStr);
		databaseHelper.execSQL(sqlStr);
	}

	public ConfigFileInfo getConfigFileInfoByFileName(String fileName)
	{
		Log.debug(this.getClass(), "getConfigFileInfoByFileName");
		String selection = DbConst.COL_FileName + "=?";
		ConfigFileInfo info = null;

		Cursor cursor = databaseHelper.query(true,DbConst.Table_Config,ConfigFileInfo.getColumns(),selection,new String[]{fileName},null,null,null,null);
		if(cursor != null
				&& cursor.moveToNext())
		{
			info =  new ConfigFileInfo(cursor);
		}
		if (cursor != null) cursor.close();
		return info;
	}


	public void addConfigFileInfo(ConfigFileInfo info)
	{
		String fileName = info.getFileName();
		String selection = DbConst.COL_FileName + "=?";

		databaseHelper.delete(DbConst.Table_Config,selection,new String[]{fileName});
		Log.debug(this.getClass(),"addUserInfo");
		long result = databaseHelper.insert(DbConst.Table_Config,null,info.getContentValues());
		Log.debug(this.getClass(),"addUserInfo result = " + result);
	}
	public void deleteAllConfigFileInfo()
	{
		databaseHelper.delete(DbConst.Table_Config,null,null);
	}

	public void updateConfigFileInfo(ConfigFileInfo info)
	{
		String fileName = info.getFileName();
		String selection = DbConst.COL_FileName + "=?";
		long ret = databaseHelper.update(DbConst.Table_Config,info.getContentValues(),selection,new String[]{fileName});
		if(ret <= 0)
		{
			addConfigFileInfo(info);
		}
	}

	public ConfigFileInfo getGroupConfigFileInfoByGroupName(String groupName)
	{
		String selection = DbConst.COL_GroupName + "=?";
		ConfigFileInfo info = null;
		Cursor cursor = databaseHelper.query(true,DbConst.Table_Group_Config,GroupInfo.getColumns(),selection,new String[]{groupName},null,null,null,null);
		if(cursor != null
				&& cursor.moveToNext())
		{
			info =  new ConfigFileInfo(cursor);
		}
		if (cursor != null) cursor.close();
		return info;
	}


	public void addGroupConfigFileInfo(ConfigFileInfo info)
	{
		String groupName = info.getFileName();
//		ContentResolver cr = ctx.getContentResolver();
		String selection = DbConst.COL_GroupName + "=?";
		databaseHelper.delete(DbConst.Table_Group_Config,selection,new String[]{groupName});
		Log.debug(this.getClass(),"addUserInfo");
		long result = databaseHelper.insert(DbConst.Table_Group_Config,null,info.getGroupContentValues());
		Log.debug(this.getClass(),"addUserInfo result = " + result);
	}

	public void cleanAllLogin()
	{
		Log.debug(this.getClass(),"cleanAllLogin");

//		databaseHelper.delete(DbConst.Table_Map_Point,null,null);
	}

	public void resetTables()
	{
		Log.debug(this.getClass(),"resetTables");
		databaseHelper.delete(DbConst.Table_LoginState,null,null);
		databaseHelper.delete(DbConst.Table_Address, "1=1", null);
		databaseHelper.delete(DbConst.Table_GroupAddress, "1=1", null);
		databaseHelper.delete(DbConst.Table_History, "1=1", null);
		databaseHelper.delete(DbConst.Table_Session, "1=1", null);
		databaseHelper.delete(DbConst.Table_Config, "1=1", null);
		databaseHelper.delete(DbConst.TABLE_MEMBER, "1=1", null);
	}
}
